﻿//using Cheyilian.Protocol.JT808;
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lails.MQClient.Demo
{
    class LocationSPDemo
    {
        static void Main()
        {
            var clientID = "consumer001";
            var appId = "demo";
            var config = new MQConfig("mq.lails.cc", "demo", "demo", clientID, appId);

            var client = CreateMQClient(config);

            #region 订阅数据

            var topic = "gps808.location.realtime.1369876543210";
            client.Connect();
            var odrsuc = client.Subscribe(topic, data =>
            {
                PrintMessage($"接收到订阅消息:{data.Length}字节");

                //var loc = ProtobufHelper.DeSerialize<Location>(data);
                //var loc = ProtobufHelper.DeSerialize<LocationEx>(data);
                Location loc = null;
                //using(var input = new MemoryStream(data))
                //{
                //    loc = Location.Parser.ParseFrom(input);
                //}

                loc = ProtobufHelper.DeSerializeParser<Location>(data);

                var info = BuildeLocationString(loc);
                PrintMessage($"定位数据:{info}");

                return true; //ACK
            });
            PrintMessage($"订阅消息[{odrsuc}]:{topic}");

            #endregion

            #region 发布数据

            var location = new Location();
            location.Lon = 113.25698;location.Lat = 23.6595;
            location.Speed = 100;
            location.Direction = 86;location.Altitude = 1000;
            location.LocateTime = DateTime.Now.ToString();//DateTime.Now;
            location.ReceiveTime = DateTime.Now.ToString(); //DateTime.Now;
            location.State = 0xffcc;location.Altitude = 0xffee;
            location.Mileage = 123456;location.OilOhm = 255;
            location.SenseSpeed = 89;location.ExVhlSignalState = 78;
            location.WLSignal = 100;location.GNSSCount = 15;
            location.Key = "1369876543210";
            location.Permutation = "JT808BD";location.Permutation = "127.0.0.1:5895";

            //var body = ProtobufHelper.Serialize<Location>(location)
            //var body = ProtobufHelper.Serialize<LocationEx>(location);

            byte[] body = null;
            //using(var stream = new MemoryStream())
            //using(var output = new CodedOutputStream(stream))
            //{
            //    location.WriteTo(output);
            //    output.Flush();
            //    body = stream.ToArray();
            //}

            body = ProtobufHelper.SerializeWriteTo<Location>(location);

            var sendSuc = client.Publish(topic, body);

            var sinfo = BuildeLocationString(location);
            PrintMessage($"发送定位消息:{sendSuc}\r\n{body.Length}字节，{sinfo}\r\n");

            #endregion


            Console.ReadLine();
        }

        /// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
        public static string BuildeLocationString(Location item)
        {
            return $"{item.Key},LT:{item.LocateTime},RT:{item.ReceiveTime},({item.Lon},{item.Lat}),速度:{item.Speed}," +
                   $"行驶记录速度:{item.SenseSpeed}," +
                   $"里程:{item.Mileage}," +
                   $"方向:{item.Direction},海拨:{item.Altitude}," +
                   $"状态:0x{((long)item.State).ToString("x").ToUpper()}," +
                   $"报警:0x{((long)item.Alarm).ToString("x").ToUpper()}," +
                   $"信号强度:{item.WLSignal},卫星个数:{item.GNSSCount}";
        }

        /// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
        public static string BuildeLocationString(LocationEx item)
        {
            return $"{item.Key},LT:{item.LocateTime},RT:{item.ReceiveTime},({item.Lon},{item.Lat}),速度:{item.Speed}," +
                   $"行驶记录速度:{item.SenseSpeed}," +
                   $"里程:{item.Mileage}," +
                   $"方向:{item.Direction},海拨:{item.Altitude}," +
                   $"状态:0x{((long)item.State).ToString("x").ToUpper()}," +
                   $"报警:0x{((long)item.Alarm).ToString("x").ToUpper()}," +
                   $"信号强度:{item.WLSignal},卫星个数:{item.GNSSCount}";
        }

        static long index = 1;
        private static void PrintMessage(string message)
        {
            Console.WriteLine($"{index++}\t{DateTime.Now}\t{message}");
        }

        /// <summary>
        /// 创建消息队列客户端
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        private static MQClient CreateMQClient(MQConfig config)
        {
            MQClient client = new RabbitMQClient(config.ServerAddr, 
                                                 config.UserName,
                                                 config.Password,
                                                 config.ClientID,
                                                 config.AppID);
            return client;
        }
    }

    /// <summary>
    /// 消息队列参数配置对象
    /// </summary>
    public class MQConfig
    {
        /// <summary>
        /// 服务地址
        /// </summary>
        public string ServerAddr;
        /// <summary>
        /// 登录名称
        /// </summary>
        public string UserName;
        /// <summary>
        /// 登录密码
        /// </summary>
        public string Password;
        /// <summary>
        /// 客户端ID
        /// </summary>
        public string ClientID;
        /// <summary>
        /// App ID
        /// </summary>
        public string AppID;

        public MQConfig()
        {

        }

        public MQConfig(string addr, string userName, string pwd, string clientId, string appId)
        {
            this.ServerAddr = addr;
            this.UserName = userName;
            this.Password = pwd;
            this.ClientID = clientId;
            this.AppID = appId;
        }
    }
}
